<template>
  <div class="btn-group">
    <el-button plain v-bind="$attrs" @click="handleExport"> 导出数据 </el-button>

    <el-radio-group v-model="state.radioValue" @change="handleDateRange" style="flex-shrink: 0">
      <el-radio-button label="当天" />
      <el-radio-button label="最近7天" />
      <el-radio-button label="最近30天" />
    </el-radio-group>

    <el-date-picker
      v-model="state.timeRange"
      type="datetimerange"
      start-placeholder="开始时间"
      end-placeholder="结束时间"
      value-format="YYYY-MM-DD HH:mm:ss"
      @change="dateChange"
      :clearable="false"
      :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
    />
  </div>
</template>

<script setup>
import { parseTime } from '@/utils/tools'

const emit = defineEmits(['update:modelValue', 'change', 'export'])
const props = defineProps({
  radioValue: {
    type: String,
    default: ''
  }
})

const state = reactive({
  timeRange: [
    parseTime(new Date(), '{y}-{m}-{d}') + ' 00:00:00',
    parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
  ],
  radioValue: '当天'
})

const dateChange = () => {
  state.radioValue = ''
  emit('update:modelValue', state.timeRange)
  emit('change')
}

/** 导出按钮操作 */
function handleExport() {
  emit('export')
}

function handleDateRange(val) {
  const end = parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
  const start = new Date()
  switch (val) {
    case '最近30天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
      state.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    case '最近7天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
      state.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    case '当天':
      state.timeRange = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    default:
      break
  }
  emit('update:modelValue', state.timeRange)
  emit('change')
}

const reset = () => {
  state.timeRange = [
    parseTime(new Date(), '{y}-{m}-{d}') + ' 00:00:00',
    parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
  ]
  state.radioValue = '当天'
  emit('update:modelValue', state.timeRange)
  emit('change')
}

defineExpose({
  reset
})
</script>

<style lang="scss" scoped>
.btn-group {
  display: flex;
  align-items: center;
}
.el-radio-group {
  margin: 0 10px;
}
</style>
